package com.dy.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:
 * @Author: 仄言in
 * @Desctiption: shiro的配置类
 * @Date: 2021/6/1 17:44
 * @Version 1.0 (版本)
 */
@Configuration
public class ShiroConfig {
    /**
     * 自定义Realm
     * @return myRealm
     */
    @Bean
    public MyRealm getMyRealm(){
        MyRealm myRealm = new MyRealm();
        //注入密码加密
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myRealm;
    }

    /**
     * 密码加密算法设置
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //散列的次数
        hashedCredentialsMatcher.setHashIterations(1);
        return hashedCredentialsMatcher;
    }

    /**
     * SecurityManager安全管理器
     * @param myRealm
     * @return securityManager
     */
    @Bean
    public DefaultWebSecurityManager getSecurityManager(MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    /**
     * shiro过滤器
     * @param securityManager
     * @return filter
     */
    @Bean
    public ShiroFilterFactoryBean shiroFiler(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
        filter.setSecurityManager(securityManager);
        //配置过滤规则
        //auto:匿名通过
        //authc:其他不通过
        Map<String,String> filterMap=new HashMap<>();
        filterMap.put("/admin/blogs.html","authc");
        filterMap.put("/admin/home.html","authc");
        filterMap.put("/admin/_fragments_after.html","authc");
        filterMap.put("/admin/blogsinput.html","authc");
//        filterMap.put("/blogsinput","authc");
//        filterMap.put("/blogs","authc");
//        filterMap.put("/home","authc");
//        filterMap.put("/blogs","authc");
        filterMap.put("/blog/queryBlog","authc");
        filter.setFilterChainDefinitionMap(filterMap);
        //默认的访问路径
        filter.setLoginUrl("/index.html");
        return filter;
    }
}
